package com.pic.mgt.monitor.parser.haishin;

import java.io.File;

import org.apache.commons.lang.StringUtils;

import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.parser.FormatParser;

public class AppointedTargetMessageTransactionFileParser extends FormatParser {
	private int messageTerminalIdStartFromChar;
	private char[] haishinOutboxPublicStrCharArray;
	private String messageConfirmationFilenameEndWith;
	
	public AppointedTargetMessageTransactionFileParser(String haishinOutboxPublic) {
		super();
		
		haishinOutboxPublicStrCharArray = haishinOutboxPublic.toCharArray();
	}

	@Override
	public Object parse(Object _confirmationFile) throws WrongUnitFormatException {
		// 確認是否為 File 型態
		// throws WrongUnitFormatException
		super.checkObjectType(_confirmationFile, File.class);
		
		File confirmationFile = (File)_confirmationFile;
		
		// 取得確認檔的目錄位置
		File confirmationFileFolderPath = confirmationFile.getParentFile();
		
		// 取得移除掉Suffix後的確認檔檔名,並轉換成為 char array
		char[] confirmationFilenameRemovedSuffixCharArray =
											StringUtils.removeEnd(
													confirmationFile.getName(),
													this.messageConfirmationFilenameEndWith
													).toCharArray();
		
		try {
			int pos = this.messageTerminalIdStartFromChar;
			for (int i=0;i<haishinOutboxPublicStrCharArray.length;i++) {
				confirmationFilenameRemovedSuffixCharArray[pos-1] = haishinOutboxPublicStrCharArray[i];
				pos++;
			}
		} catch (IndexOutOfBoundsException e) {
			throw new WrongUnitFormatException(
					"The confirmation filename '" + confirmationFile.getName() +
					"' of message is not correct!");
		}
		
		File transactionFile = new File(confirmationFileFolderPath.getAbsolutePath(),
								        new String(confirmationFilenameRemovedSuffixCharArray));
		if (!transactionFile.exists()) {
			throw new WrongUnitFormatException(
									"Transaction file doesn't exist.");
		}
		
		return transactionFile;
	}
	
	// --- getter and setter ---

	public void setMessageTerminalIdStartFromChar(int messageTerminalIdStartFromChar) {
		this.messageTerminalIdStartFromChar = messageTerminalIdStartFromChar;
	}

	public void setMessageConfirmationFilenameEndWith(
			String messageConfirmationFilenameEndWith) {
		this.messageConfirmationFilenameEndWith = messageConfirmationFilenameEndWith;
	}

}
